<template>
	<view>
		<u-loading-page :loading="uploading" loading-text="图片上传中..."></u-loading-page>
		<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
			:maxCount="maxCount" :previewFullImage="true"></u-upload>
	</view>

</template>

<script>
	import ossApi from "@/api/thirdParty/oss.js";
	import uuidApi from "@/utils/uuid.js"
	export default {
		name: "ImageUpload",
		props: {
			value: [String, Object, Array],
			// 图片最大上传数量
			maxCount: {
				type: String,
				default: "1"
			}
		},
		data() {
			return {
				fileList1: [],
				uploadUrl: "http://smart-scheduling-system-13184.oss-cn-beijing.aliyuncs.com",
				// 图片数量
				pictureNum: 0,
				// 是否显示加载中
				uploading: false,
			};
		},
		created() {
			// console.log("this.value:" + JSON.stringify(this.value))
			if (this.value != null) {
				this.fileList1 = [];
				for (var i = 0; i < this.value.length; i++) {
					if (this.value[i] != '') {
						this.fileList1.push({
							url: this.value[i]
						});
					}
				}
			}
			this.pictureNum = this.fileList1.length;
			// console.log("this.fileList1:" + JSON.stringify(this.fileList1))
		},
		watch: {
			// 监听数据变化
			value: {
				handler(newValue, oldValue) {
					this.fileList1 = [];
					for (var i = 0; i < newValue.length; i++) {
						if (newValue[i] != '') {
							this.fileList1.push({
								url: newValue[i]
							});
						}
					}
					this.pictureNum = this.fileList1.length;
				},
				immediate: true,
			}
		},
		methods: {
			// 删除图片
			deletePic(event) {
				let deletIndex = event.index;
				this[`fileList${event.name}`].splice(deletIndex, 1);
				let urlList = [];
				for (var i = 0; i < this.fileList1.length; i++) {
					urlList.push(this.fileList1[i].url);
				}
				this.$emit("input", urlList);
				this.pictureNum--;
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			// 上传图片
			uploadFilePromise(url) {
				this.uploading = true;
				return new Promise((resolve, reject) => {
					let dataObj = {
						policy: '',
						signature: '',
						key: '',
						OSSAccessKeyId: '',
						dir: '',
						host: ''
					};
					ossApi.getPolicy()
						.then((response) => {
							// console.log('policy response:' + JSON.stringify(response))
							// debugger;
							dataObj.policy = response.data.policy
							dataObj.signature = response.data.signature
							dataObj.OSSAccessKeyId = response.data.accessId
							let prefix = response.data.dir + uuidApi.getUUID();
							dataObj.key = prefix + '_${filename}'
							dataObj.dir = response.data.dir
							dataObj.host = response.data.host
							console.log('获取policy成功')
							let a = uni.uploadFile({
								url: this.uploadUrl,
								filePath: url,
								name: 'file',
								formData: dataObj,
								success: (res) => {
									console.log('图片上传res:' + JSON.stringify(res))
									console.log('图片上传成功，url：' + JSON.stringify(url));
									// 拼接出可以直接访问的oss图片
									// "http://tmp/" windows电脑的前缀 （电脑微信小程序）
									// "wxfile://" 安卓微信的前缀
									// "blob:http://localhost:8080/" 电脑网页前缀
									// 未知 "安卓手机前缀"

									// let picUrl = dataObj.host +
									// 	'/' +
									// 	dataObj.key.replace('${filename}', url.indexOf(
									// 		"http://tmp/") != -1 ? url.replace(
									// 		"http://tmp/", '') : url.replace(
									// 		"wxfile://", ''));
									console.log('prefix：' + prefix);
									let picUrl = dataObj.host + '/' + prefix + '_' + this
										.fileList1[this.fileList1
											.length - (this.fileList1.length -
												this.pictureNum)].name;
									console.log('picUrl：' + picUrl);

									// console.log('picUrl：' + JSON.stringify(picUrl));
									console.log('this.fileList1：' + JSON.stringify(this
										.fileList1));
									console.log('this.pictureNum：' + this.pictureNum);
									// 设置之后，才可以预览图片
									this.fileList1[this.fileList1.length - (this.fileList1.length -
										this.pictureNum)].url = picUrl;
									this.pictureNum++;
									let urlList = [];
									for (var i = 0; i < this.fileList1.length; i++) {
										urlList.push(this.fileList1[i].url);
									}
									// console.log("urlList:" + JSON.stringify(urlList))
									this.$emit("input", urlList);
									setTimeout(() => {
										resolve(res)
									}, 1000)
								}
							});
							this.uploading = false;
							resolve(true)
						})
						.catch((err) => {
							// console.log('获取policy失败')
							reject(false)
						})

				})
			},
		}
	}
</script>

<style>

</style>